package org.jeecg.modules.demo.utils;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;


public class AesCbcUtil {

    private static final String ENCODING = "UTF-8";
    private static final String AES_ALGORITHM = "AES";
    private static final String CIPHER_PADDING = "AES/CBC/PKCS5Padding";
    private static final String ivParameter = "94e9d0c7328e27ab";

    /**
     *     加密
     */
    public static String encrypt(String content, String sKey, String ivParameter) {
        try {
            Cipher cipher = Cipher.getInstance(CIPHER_PADDING);
            byte[] raw = sKey.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, AES_ALGORITHM);
            // 使用CBC模式，需要一个向量iv，可增加加密算法的强度
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
            return Base64.encodeBase64String(encrypted);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *     解密
     */
    public static String decrypt(String sSrc,String key, String ivParameter) {
        try {
            byte[] raw = key.getBytes(StandardCharsets.US_ASCII);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, AES_ALGORITHM);
            Cipher cipher = Cipher.getInstance(CIPHER_PADDING);
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            // 先用base64解密
            byte[] encrypted1 = Base64.decodeBase64(sSrc);
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original, StandardCharsets.UTF_8);
        }
        catch (Exception e) {
            //logger.error("AES解密异常：", e);
            throw new RuntimeException("AES解密异常");
        }
    }

    /**
     * AES加密
     * @param content 待加密内容
     * @param aesKey  密码
     * @return
     */
    public static String encrypt(String content, String aesKey){
        return encrypt(content,aesKey,ivParameter);
    }

    /**
     * 解密
     *
     * @param content 待解密内容
     * @param aesKey  密码
     * @return
     */
    public static String decrypt(String content, String aesKey){
        return decrypt(content,aesKey,ivParameter);
    }

    public static void main(String[] args) throws Exception {
    }
}
